import java.util.Objects;
import java.util.PriorityQueue;

/*abstract class MyTimerTask implements Runnable{

    @Override
    public abstract void run();
}*/
class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable task;
    //记录任务执行所要等待的时间
    private long time;
    public MyTimerTask(Runnable task,long time){
        this.task=task;
        this.time=time;
    }
    public long getTime(){
        return this.time;
    }
    public Runnable getTask() {
        return this.task;
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time-o.time);
    }
}

class MyTimer {
    private Object locker=new Object();
    private PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
    public MyTimer() {
        Thread t=new Thread(()->{
            while (true){
                synchronized(locker){
                    while (queue.isEmpty()){
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask task=queue.peek();
                    if(task.getTime()>System.currentTimeMillis()){
                        try {
                            locker.wait(task.getTime()-System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    else {
                        //时间到了执行任务
                        task.getTask().run();
                        queue.poll();
                    }
                }
            }
        });
        t.start();
    }
    public void schedule(Runnable task,long delay) {
        synchronized (locker){
            MyTimerTask timerTask=new MyTimerTask(task,System.currentTimeMillis()+delay);
            queue.offer(timerTask);
            locker.notify();
        }
    }
}
public class Demo5 {
    public static void main(String[] args) {
        MyTimer timer=new MyTimer();
        timer.schedule(()->{
            System.out.println(1);
        },1000);
        timer.schedule(()->{
            System.out.println(2);
        },2000);
        timer.schedule(()->{
            System.out.println(3);
        },3000);
    }
}
